//
//  HHPLivingViewController.m
//  HHPLivingVideo
//
//  Created by 韩红坡 on 2017/3/29.
//  Copyright © 2017年 韩红坡. All rights reserved.
//

#import "HHPLivingViewController.h"
#import "HHPLivingViewModel.h"
#import "HHPLiveModel.h"

@interface HHPLivingViewController () <UIScrollViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) HHPTableViewManager *tableViewManager;

@property (nonatomic, strong) HHPLivingViewModel *livingViewModel;

@property (nonatomic, strong) UIView *liveView;

/** 直播播放器 */
@property (nonatomic, strong) IJKFFMoviePlayerController *moviePlayer;

@property (nonatomic, strong) HHPLiveModel *currentLiveModel;

@property (nonatomic, assign) CGPoint point;

@end

@implementation HHPLivingViewController
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initViews];
    
    [self reloadData];
    
    self.currentLiveModel = [self.liveArray objectAtIndex:self.currentLiveIndex];
    
    [self.tableView scrollToRow:self.currentLiveIndex inSection:0 atScrollPosition:UITableViewScrollPositionTop animated:NO];
    
    self.liveView.top = self.tableView.contentOffset.y;
    
    [self playLiveFlv];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.moviePlayer pause];
    [self.moviePlayer stop];
}

#pragma mark - private methods
- (void)initViews
{
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.liveView];
    
    [self layoutPageSubviews];
}

- (void)layoutPageSubviews
{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self.view);
    }];
}

- (void)reloadData
{
    [self.tableView hhp_reloadDataWithBlock:^{
        [self.tableView hhp_addCells:self.liveArray];
    }];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat currentOffsetY = scrollView.contentOffset.y;
    
    int page = currentOffsetY / ScreenHeight;
    
    NSLog(@"%s, %d, page = %d, curPage = %ld", __func__, __LINE__, page, self.currentLiveIndex);
    
    page = page < 0 ? 0 : page;
    
    if (self.currentLiveIndex != page) {
        self.currentLiveIndex = page;
        
        self.currentLiveModel = [self.liveArray objectAtIndex:page];
        
        self.liveView.top = currentOffsetY;
        
        [self playLiveFlv];
    }
}

- (void)playLiveFlv
{
    if (_moviePlayer) {
        [_moviePlayer shutdown];
        [_moviePlayer.view removeFromSuperview];
        _moviePlayer = nil;
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    
    IJKFFOptions *options = [IJKFFOptions optionsByDefault];
    
    //开启硬件解码
    [options setPlayerOptionIntValue:1 forKey:@"videotoolbox"];
    // 帧速率(fps) （可以改，确认非标准桢率会导致音画不同步，所以只能设定为15或者29.97）
    [options setPlayerOptionIntValue:29.97 forKey:@"r"];
    // 设置音量大小，256为标准音量。（要设置成两倍音量时则输入512，依此类推）
    [options setPlayerOptionIntValue:512 forKey:@"vol"];
    // 最大fps
//    [options setPlayerOptionIntValue:30 forKey:@"max-fps"];
    // 跳帧开关
//    [options setPlayerOptionIntValue:0 forKey:@"framedrop"];
    // 指定最大宽度
//    [options setPlayerOptionIntValue:960 forKey:@"videotoolbox-max-frame-width"];
    // 自动转屏开关
//    [options setFormatOptionIntValue:0 forKey:@"auto_convert"];
    // 重连次数
//    [options setFormatOptionIntValue:1 forKey:@"reconnect"];
    // 超时时间，timeout参数只对http设置有效，若果你用rtmp设置timeout，ijkplayer内部会忽略timeout参数。rtmp的timeout参数含义和http的不一样。
//    [options setFormatOptionIntValue:30 * 1000 * 1000 forKey:@"timeout"];
    //可以打开h265硬解;
//    ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-hevc", 1);
    
    IJKFFMoviePlayerController *moviePlayer = [[IJKFFMoviePlayerController alloc] initWithContentURLString:self.currentLiveModel.flv withOptions:options];
    
    moviePlayer.scalingMode = IJKMPMovieScalingModeAspectFill;
    // 设置自动播放(必须设置为NO, 防止自动播放, 才能更好的控制直播的状态)
    moviePlayer.shouldAutoplay = NO;
    // 默认不显示
    moviePlayer.shouldShowHudView = NO;
    
    [self.liveView addSubview:moviePlayer.view];

    [moviePlayer.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self.liveView);
    }];
    
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(10, 30, ScreenWidth - 10, 50);
    label.textColor = [UIColor redColor];
    label.font = Font(16);
    label.tag = 1000;
    label.text = self.currentLiveModel.myname;
    
    [moviePlayer.view addSubview:label];
    
//    [MBProgressHUD showLoadingMessage:@"努力加载中...."];
    [moviePlayer prepareToPlay];
    
    [self initObserver];
    
    self.moviePlayer = moviePlayer;
}

- (void)initObserver
{
    // 监听视频是否播放完成
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didFinish) name:IJKMPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadStateDidChange) name:IJKMPMoviePlayerLoadStateDidChangeNotification object:self.moviePlayer];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackStateDidChange) name:IJKMPMoviePlayerPlaybackStateDidChangeNotification object:self.moviePlayer];
}

#pragma mark - Notification method
- (void)playbackStateDidChange
{
    HHPLog(@"%s, %d, playbackState = %ld", __func__, __LINE__, self.moviePlayer.playbackState);
    if (self.moviePlayer.playbackState == IJKMPMoviePlaybackStatePlaying) {
       
    }
}

- (void)loadStateDidChange
{
    HHPLog(@"%s, %d loadState = %ld", __func__, __LINE__, self.moviePlayer.loadState);
    if ((self.moviePlayer.loadState & IJKMPMovieLoadStatePlaythroughOK) != 0) {
        if (!self.moviePlayer.isPlaying) {
            HHPLog(@"%s, %d isPlaying", __func__, __LINE__);
            [self.moviePlayer play];
        }else{
            HHPLog(@"%s, %d 如果是网络状态不好, 断开后恢复, 也需要去掉加载", __func__, __LINE__);
            // 如果是网络状态不好, 断开后恢复, 也需要去掉加载
        }
        [MBProgressHUD hideHUD];
    }else if (self.moviePlayer.loadState & IJKMPMovieLoadStateStalled){ // 网速不佳, 自动暂停状态
//        [MBProgressHUD showLoadingMessage:@"努力加载中..."];
        HHPLog(@"%s, %d 网速不佳, 自动暂停状态", __func__, __LINE__);
    }
}

- (void)didFinish
{
    NSLog(@"加载状态...%ld %ld %s", self.moviePlayer.loadState, self.moviePlayer.playbackState, __func__);
    // 因为网速或者其他原因导致直播stop了, 也要显示GIF
    if (self.moviePlayer.loadState & IJKMPMovieLoadStateStalled) {
//        [MBProgressHUD showLoadingMessage:@"努力加载中..."];
        return;
    }
    
    [self.livingViewModel fetchLiveFlvDataWithUrl:self.currentLiveModel.flv successBlock:^{
        HHPLog(@"请求成功%@, 等待继续播放")
    } errorBlock:^(NSError *error) {
        NSLog(@"请求失败, 加载失败界面, 关闭播放器%@", error);
        [self.moviePlayer shutdown];
        [self.moviePlayer.view removeFromSuperview];
        self.moviePlayer = nil;
        [UIAlertController hhp_showAlertControllerWithPreferredStyle:UIAlertControllerStyleAlert WithTitle:@"直播已结束" message:nil cancelButtonTitle:@"退出" otherButtonTitles:nil handler:^(NSInteger buttonIndex) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
    }];
}

#pragma mark - getter ans setter
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self.tableViewManager;
        _tableView.dataSource = self.tableViewManager;
        _tableView.backgroundColor = ViewBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.pagingEnabled = YES;
        _tableView.showsVerticalScrollIndicator = NO;
    }
    
    return _tableView;
}

- (HHPTableViewManager *)tableViewManager
{
    if (!_tableViewManager) {
        _tableViewManager = [[HHPTableViewManager alloc] init];
        _tableViewManager.delegate = self;
    }
    
    return _tableViewManager;
}

- (void)setLiveArray:(NSMutableArray *)liveArray
{
    _liveArray = [liveArray mutableCopy];
    
    for (HHPLiveModel *model in liveArray) {
        model.cellType = LiveCellTypeLiving;
    }
}

- (UIView *)liveView
{
    if (!_liveView) {
        _liveView = [[UIView alloc] initWithFrame:self.view.bounds];
        _liveView.backgroundColor = [UIColor clearColor];
    }
    
    return _liveView;
}

- (HHPLivingViewModel *)livingViewModel
{
    if (!_livingViewModel) {
        _livingViewModel = [[HHPLivingViewModel alloc] init];
    }
    
    return _livingViewModel;
}

@end
